package handlers

import (
	"context"
	"ourplansystem/server/ent"
	"ourplansystem/server/ent/note"
	"ourplansystem/server/models"
	"strconv"
	"time"

	"github.com/gofiber/fiber/v2"
)

// NoteHandler 情侣小纸条处理器
type NoteHandler struct {
	client *ent.Client
}

// NewNoteHandler 创建情侣小纸条处理器
func NewNoteHandler(client *ent.Client) *NoteHandler {
	return &NoteHandler{client: client}
}

// CreateNoteRequest 创建小纸条请求
type CreateNoteRequest struct {
	Content    string `json:"content"`
	FromUserID int64  `json:"from_user_id"`
	ToUserID   int64  `json:"to_user_id"`
}

// UpdateNoteRequest 更新小纸条请求
type UpdateNoteRequest struct {
	IsRead bool `json:"is_read"`
}

// GetNotes 获取所有未删除的小纸条
func (h *NoteHandler) GetNotes(c *fiber.Ctx) error {
	ctx := context.Background()
	notes, err := h.client.Note.Query().
		Where(note.DeletedAtIsNil()).
		WithFromUser().
		WithToUser().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取小纸条列表失败")
	}

	return models.Success(c, notes)
}

// GetNote 获取单个小纸条
func (h *NoteHandler) GetNote(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的小纸条ID")
	}

	noteObj, err := h.client.Note.Get(ctx, id)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "小纸条不存在")
		}
		return models.InternalServerError(c, "获取小纸条失败")
	}

	return models.Success(c, noteObj)
}

// GetReceivedNotes 获取指定用户收到的小纸条
func (h *NoteHandler) GetReceivedNotes(c *fiber.Ctx) error {
	ctx := context.Background()
	userID, err := strconv.ParseInt(c.Params("userId"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的用户ID")
	}

	notes, err := h.client.Note.Query().
		Where(note.ToUserIDEQ(userID), note.DeletedAtIsNil()).
		WithFromUser().
		WithToUser().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取小纸条失败")
	}

	return models.Success(c, notes)
}

// GetSentNotes 获取指定用户发送的小纸条
func (h *NoteHandler) GetSentNotes(c *fiber.Ctx) error {
	ctx := context.Background()
	userID, err := strconv.ParseInt(c.Params("userId"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的用户ID")
	}

	notes, err := h.client.Note.Query().
		Where(note.FromUserIDEQ(userID), note.DeletedAtIsNil()).
		WithFromUser().
		WithToUser().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取小纸条失败")
	}

	return models.Success(c, notes)
}

// CreateNote 创建小纸条
func (h *NoteHandler) CreateNote(c *fiber.Ctx) error {
	ctx := context.Background()
	var req CreateNoteRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	if req.Content == "" {
		return models.BadRequest(c, "内容不能为空")
	}

	if req.FromUserID == 0 {
		return models.BadRequest(c, "发送者ID不能为空")
	}

	if req.ToUserID == 0 {
		return models.BadRequest(c, "接收者ID不能为空")
	}

	noteObj, err := h.client.Note.
		Create().
		SetContent(req.Content).
		SetFromUserID(req.FromUserID).
		SetToUserID(req.ToUserID).
		Save(ctx)

	if err != nil {
		return models.InternalServerError(c, "创建小纸条失败")
	}

	return models.SuccessWithMessage(c, "创建成功", noteObj)
}

// UpdateNote 更新小纸条（主要是标记已读）
func (h *NoteHandler) UpdateNote(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的小纸条ID")
	}

	var req UpdateNoteRequest
	if err := c.BodyParser(&req); err != nil {
		return models.BadRequest(c, "请求参数错误")
	}

	noteObj, err := h.client.Note.
		UpdateOneID(id).
		SetIsRead(req.IsRead).
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "小纸条不存在")
		}
		return models.InternalServerError(c, "更新小纸条失败")
	}

	return models.SuccessWithMessage(c, "更新成功", noteObj)
}

// DeleteNote 软删除小纸条
func (h *NoteHandler) DeleteNote(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的小纸条ID")
	}

	// 软删除：设置 deleted_at 为当前时间
	now := time.Now()
	_, err = h.client.Note.UpdateOneID(id).
		SetDeletedAt(now).
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "小纸条不存在")
		}
		return models.InternalServerError(c, "删除小纸条失败")
	}

	return models.SuccessWithMessage(c, "删除成功", nil)
}

// GetDeletedNotes 获取所有已删除的小纸条（回收站）
func (h *NoteHandler) GetDeletedNotes(c *fiber.Ctx) error {
	ctx := context.Background()
	notes, err := h.client.Note.Query().
		Where(note.DeletedAtNotNil()).
		WithFromUser().
		WithToUser().
		All(ctx)
	if err != nil {
		return models.InternalServerError(c, "获取已删除小纸条失败")
	}

	return models.Success(c, notes)
}

// RestoreNote 恢复已删除的小纸条
func (h *NoteHandler) RestoreNote(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的小纸条ID")
	}

	// 恢复：清空 deleted_at
	_, err = h.client.Note.UpdateOneID(id).
		ClearDeletedAt().
		Save(ctx)

	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "小纸条不存在")
		}
		return models.InternalServerError(c, "恢复小纸条失败")
	}

	return models.SuccessWithMessage(c, "恢复成功", nil)
}

// PermanentDeleteNote 永久删除小纸条
func (h *NoteHandler) PermanentDeleteNote(c *fiber.Ctx) error {
	ctx := context.Background()
	id, err := strconv.ParseInt(c.Params("id"), 10, 64)
	if err != nil {
		return models.BadRequest(c, "无效的小纸条ID")
	}

	err = h.client.Note.DeleteOneID(id).Exec(ctx)
	if err != nil {
		if ent.IsNotFound(err) {
			return models.NotFound(c, "小纸条不存在")
		}
		return models.InternalServerError(c, "永久删除小纸条失败")
	}

	return models.SuccessWithMessage(c, "永久删除成功", nil)
}
